package com.gosun.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author liuguibin
 * @date 2021-01-09 22:00
 */
public class HttpClientUtil {
    protected static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String getDocData() {
        //1.获得一个httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.生成一个get请求
        HttpGet httpGet = new HttpGet("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
        //3.执行get请求并返回结果
        CloseableHttpResponse response = null;
        InputStream xmlContent = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            logger.info("请求返回状态码：{}", response.getStatusLine().getStatusCode());
            xmlContent = entity.getContent();
            logger.info("请求响应成功！");
            return inputStreamToString(xmlContent);
        } catch (IOException e) {
            logger.error("http请求错误！");
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("response关闭异常！");
                    //e.printStackTrace();
                }
            }

            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("httpClient关闭异常！");
                    //e.printStackTrace();
                }

            }

        }
        logger.error("空指针异常！");
        return inputStreamToString(xmlContent);
    }


    public static String inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            logger.error("文件流读取错误！");
            //e.printStackTrace();
        }

        return total.toString();
    }

}
